<template>
  <a-space :wrap="true" class="layout_cpu">
    <div :id="`cpuMap-${i}`" v-for="i in 16" :key="i" style="width: 150px; margin-top: 10px; height: 200px; border: 2px dashed #6a737a;"></div>
  </a-space>
</template>

<script setup>
import { onMounted, ref,onUnmounted } from 'vue';
import { getCpuLoad } from '@/api/cpuLoad';
import * as echarts from 'echarts';

const cpuLoad = ref([]);
const chartdoms = ref([]);
let isFetching = ref(true);

onMounted(() => {
  initChart();  // 初始化图表只需进行一次
  getCpuLoadData(); // 定期获取cpu数据
});
onUnmounted(() => {
  isFetching.value = false; // 设置 isFetching 为 false，停止递归
});

// 初始化16个图表，以免每次请求都重新初始化
const initChart = () => {
  for (let i = 1; i <= 16; i++) {
    let DOM = document.getElementById(`cpuMap-${i}`);
    let myChart = echarts.init(DOM);
    chartdoms.value.push(myChart);
  }
};

// 获取数据
const getCpuLoadData = async () => {
  if (!isFetching.value) return;

  const res = await getCpuLoad();
  let data = res.data.data;

  for (let i = 0; i < 16; i++) {
    if (!cpuLoad.value[i]) {
      cpuLoad.value[i] = [];
    }
// 最多放5个数据，避免oom(内存溢出)，超过5个数据，就删除最前的数据
cpuLoad.value[i].push(data[i]);
if (cpuLoad.value[i].length > 10) {
  cpuLoad.value[i] = cpuLoad.value[i].slice(-10);
}
drawCpuLoad(i + 1, cpuLoad.value[i]);

  }
 await getCpuLoadData();   // 每秒获取一次数据
};

// 画图
const drawCpuLoad = (index, cpuData) => {
  let myChart = chartdoms.value[index - 1];
  let option = {
    grid: {
      left: "0",
      right: "0",
      bottom: "20",
      top: "0"
    },
    title: {
      text: `cpu-${index}`,
      textStyle: {
        color: '#0F9B0F',
        textBorderColor: '#38F9D7',
      },
    },
    xAxis: {
      type: 'category',
      show: true,
      data: new Array(cpuData.length).fill(''), // 动态生成X轴数据
      splitLine: {
        show: true,
        lineStyle: {
          color: ['#ccc'],
          width: 1,
          type: 'solid'
        }
      }
    },
    yAxis: {
      type: 'value',
      show: false,
      mix:0,
      max:1
    },
    series: [
      {
        data: cpuData,
        smooth: true,
        type: 'line', // 修改为 'area'
        itemStyle: {
          color: 'auto', // 使用 visualMap 定义的颜色
        },
        areaStyle: {
          opacity: 0.3, // 设置面积图的透明度
        },
      },
    ],
  };
  option && myChart.setOption(option);
};
</script>

<style scoped>
/* Your styles here */
.layout_cpu {
  display: flex;
  justify-content: center;
  align-content: center;
}
</style>